import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/event/terminal_number_update_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_detail_info_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/widgets/binding_terminal_auto_switch_dialog.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/widgets/camera_distance_widget.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/event/terminal_list_refresh_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/new_terminal_list_page.dart';
import 'package:e_reception_flutter/utils/common_select_util.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import '../../app_main.dart';
import 'bean/binding_terminal_edit_upload_bean.dart';
import 'bean/binding_terminal_type.dart';
import 'binding_terminal_view_model.dart';

/// 绑定终端更多设置页面
class BindTerminalMoreSettingsPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "BindTerminalMoreSettingsPage";
  final String hsn;
  final BindingTermialEditUploadBean uploadBean;
  const BindTerminalMoreSettingsPage({Key key, this.hsn, this.uploadBean})
      : super(key: key);

  @override
  _BindTerminalMoreSettingsPageState createState() =>
      _BindTerminalMoreSettingsPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context, String hsn, BindingTermialEditUploadBean uploadBean) {
    {
      return RouterUtils.routeForFutureResult(
        context,
        BindTerminalMoreSettingsPage(
          hsn: hsn,
          uploadBean: uploadBean,
        ),
        routeName: BindTerminalMoreSettingsPage.ROUTER,
      );
    }
  }
}

class _BindTerminalMoreSettingsPageState extends BaseState<BindTerminalMoreSettingsPage> {
  BindingTerminalViewModel _viewModel;
  ValueNotifier<BindingTermialEditUploadBean> _uploadValueNotifier;
  double _cameraStartValue;
  double _faceSizeValue;
  @override
  void initState() {
    super.initState();
    _viewModel = BindingTerminalViewModel(this);
    _uploadValueNotifier = ValueNotifier(null);
    _viewModel.saveController.listen((t) {
      VgEventBus.global.send(new TerminalListRefreshEvent());
      VgEventBus.global.send(new TerminalNumberUpdateEvent("新增绑定终端"));
      RouterUtils.pushAndRemoveUntil(context, NewTerminalListPage(), AppMain.ROUTER);
      // RouterUtils.popUntil(context, "NewTerminalListPage",);
      // TerminalDetailInfoPage.navigatorPush(context, widget?.hsn);
    });
    _cameraStartValue = widget?.uploadBean?.getCameraStartDistanceValue();
    _faceSizeValue = widget?.uploadBean?.getFaceSizeDistanceValue();
    Future((){
      VgToolUtils.removeAllFocus(context);
    });
  }

  @override
  void dispose() {
    _uploadValueNotifier?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: _toInfoWidget(),
    );
  }

  Widget _toInfoWidget(){
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        SizedBox(height: 10,),
        Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            //人脸识别框大小
            _toFaceSize(),
            SizedBox(height: 15,),
            //摄像头启动距离
            // _toCameraStartDistance(),
            _toNewCameraStartDistance(),
            SizedBox(height: 15,),
            //刷脸打卡间距
            _toPunchInInterval(),
            SizedBox(height: 15,),
            //自动开关机
            _toAutoOnOff(),
          ],
        ),
        Spacer(),
        GestureDetector(
          child: Container(
            margin: EdgeInsets.symmetric(horizontal: 15),
            child: Container(
              height: 40,
              alignment: Alignment.center,
              child: Text(
                "完成",
                style: TextStyle(
                  color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                  fontSize: 15,
                ),
              ),
            ),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(8)),
                color: ThemeRepository.getInstance().getPrimaryColor_1890FF()
            ),
          ),
          onTap: (){
            String msg = widget?.uploadBean?.checkVerify();
            if(StringUtils.isEmpty(msg)){
              _viewModel?.saveTerminalInfo(context, widget?.uploadBean);
              return;
            }
            VgToastUtils.toast(context, msg);
          },
        ),
        SizedBox(
          height: 30 + ScreenUtils.getBottomBarH(context),
        ),
      ],
    );
  }

  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      title: "更多设置",
      isShowBack: true,
    );
  }

  double _getDistance(double value){
    if(0.0 == value){
      return 1.0;
    }
    if(1.0 == value){
      return 1.5;
    }
    if(2.0 == value){
      return 2.0;
    }
    if(3.0 == value){
      return 2.5;
    }
    if(4.0 == value){
      return 3.0;
    }
    return 2.0;
  }

  int _getFaceSize(double value){
    if(0.0 == value){
      return 0;
    }
    if(1.0 == value){
      return 1;
    }
    if(2.0 == value){
      return 2;
    }
    return 1;
    // if(3.0 == value){
    //   return 3;
    // }
    // if(4.0 == value){
    //   return 4;
    // }
    // return 2;
  }

  ///人脸识别框大小
  Widget _toFaceSize(){
    return Container(
      height: 237,
      width: ScreenUtils.screenW(context) - 30,
      padding: EdgeInsets.symmetric(horizontal: 15),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(8)),
        color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      ),
      child: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.topLeft,
            margin: const EdgeInsets.only(top: 13, bottom: 15),
            child: Text(
              "人脸识别框大小",
              style: TextStyle(
                  fontSize: 14,
                  color: ThemeRepository.getInstance().getTextMinorGreyColor_808388()
              ),
            ),
          ),
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  children: [
                    _valueImage(0.0),
                    SizedBox(height: 10,),
                    _valueFrameText("小", 0.0),
                  ],
                ),
                Column(
                  children: [
                    _valueImage(1.0),
                    SizedBox(height: 10,),
                    _valueFrameText("中", 1.0),
                  ],
                ),
                Column(
                  children: [
                    _valueImage(2.0),
                    SizedBox(height: 10,),
                    _valueFrameText("大", 2.0),
                  ],
                ),
              ],
            ),
          )
          // Padding(
          //   padding: EdgeInsets.symmetric(horizontal: 13),
          //   child: SliderTheme(
          //     data: SliderThemeData(
          //         overlayShape: RoundSliderOverlayShape(overlayRadius: 16),
          //         thumbShape: ThumbShape(),
          //         trackHeight: 16,
          //         trackShape: CustomTrackShape(4),
          //         inactiveTickMarkColor: Colors.transparent,
          //         activeTickMarkColor: Colors.transparent,
          //         inactiveTrackColor: Colors.white,
          //         activeTrackColor: Colors.white,
          //         valueIndicatorColor: Colors.white),
          //     child: Slider(
          //       min: 0,
          //       max: 4,
          //       value: _faceSizeValue,
          //       divisions: 4,
          //       onChanged: (value) {
          //         setState(() {
          //           this._faceSizeValue = value;
          //         });
          //       },
          //     ),
          //   ),
          // ),
          // Center(
          //   child: Row(
          //     children: <Widget>[
          //       Container(
          //         width: (ScreenUtils.screenW(context) - 30)/5,
          //         alignment: Alignment.centerLeft,
          //         padding: EdgeInsets.only(left: 22),
          //         child: GestureDetector(
          //           onTap: () {
          //             setState(() {
          //               _faceSizeValue = 0.0;
          //               widget?.uploadBean?.faceSize =_getFaceSize(_faceSizeValue);
          //             });
          //           },
          //           child: Text(
          //               "小",
          //               style: TextStyle(
          //                   color: 0.0 == _faceSizeValue ? Color(0xff1890ff) : Color(
          //                       0xffD0E0F7),
          //                   fontSize: 13)),
          //         ),
          //       ),
          //       // _valueText("最近", 0.0),
          //       Container(
          //         width: (ScreenUtils.screenW(context) - 30)/5,
          //         alignment: Alignment.center,
          //         padding: EdgeInsets.only(right: 7.5),
          //         child: GestureDetector(
          //           onTap: () {
          //             setState(() {
          //               _faceSizeValue = 1.0;
          //               widget?.uploadBean?.faceSize =_getFaceSize(_faceSizeValue);
          //             });
          //           },
          //           child: Text(
          //               "较小",
          //               style: TextStyle(
          //                   color: 1.0 == _faceSizeValue ? Color(0xff1890ff) : Color(
          //                       0xffD0E0F7),
          //                   fontSize: 13)),
          //         ),
          //       ),
          //       Container(
          //         width: (ScreenUtils.screenW(context) - 30)/5,
          //         alignment: Alignment.center,
          //         child: GestureDetector(
          //           onTap: () {
          //             setState(() {
          //               _faceSizeValue = 2.0;
          //               widget?.uploadBean?.faceSize =_getFaceSize(_faceSizeValue);
          //             });
          //           },
          //           child: Text(
          //               "适中",
          //               style: TextStyle(
          //                   color: _faceSizeValue == 2.0 ? Color(0xff1890ff) : Color(
          //                       0xffD0E0F7),
          //                   fontSize: 13)),
          //         ),
          //       ),
          //       Container(
          //         width: (ScreenUtils.screenW(context) - 30)/5,
          //         alignment: Alignment.center,
          //         padding: EdgeInsets.only(left: 7.5),
          //         child: GestureDetector(
          //           onTap: () {
          //             setState(() {
          //               _faceSizeValue = 3.0;
          //               widget?.uploadBean?.faceSize =_getFaceSize(_faceSizeValue);
          //             });
          //           },
          //           child: Text(
          //               "较大",
          //               style: TextStyle(
          //                   color: 3.0 == _faceSizeValue ? Color(0xff1890ff) : Color(
          //                       0xffD0E0F7),
          //                   fontSize: 13)),
          //         ),
          //       ),
          //       Container(
          //         width: (ScreenUtils.screenW(context) - 30)/5,
          //         alignment: Alignment.centerRight,
          //         padding: EdgeInsets.only(right: 22),
          //         child: GestureDetector(
          //           onTap: () {
          //             setState(() {
          //               _faceSizeValue = 4.0;
          //               widget?.uploadBean?.faceSize =_getFaceSize(_faceSizeValue);
          //             });
          //           },
          //           child: Text(
          //               "大",
          //               style: TextStyle(
          //                   color: 4.0 == _faceSizeValue ? Color(0xff1890ff) : Color(
          //                       0xffD0E0F7),
          //                   fontSize: 13)),
          //         ),
          //       ),
          //     ],
          //   ),
          // ),
          // SizedBox(height: 6,),
          // Container(
          //   margin: EdgeInsets.symmetric(horizontal: 14),
          //   child: Row(
          //     children: <Widget>[
          //       _valueImage(0.0),
          //       _valueImage(1.0),
          //       _valueImage(2.0),
          //       _valueImage(3.0),
          //       _valueImage(4.0)
          //     ],
          //   ),
          // ),
        ],
      ),
    );
  }

  ///摄像头启动距离
  Widget _toNewCameraStartDistance(){
    return Container(
      height: 105,
      width: ScreenUtils.screenW(context) - 30,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(8)),
        color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      ),
      child: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.topLeft,
            margin: const EdgeInsets.only(top: 13,left: 15, bottom: 7),
            child: Text(
              "摄像头启动距离",
              style: TextStyle(
                  fontSize: 14,
                  color: ThemeRepository.getInstance().getTextMinorGreyColor_808388()
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 13),
            child: SliderTheme(
              data: SliderThemeData(
                  overlayShape: RoundSliderOverlayShape(overlayRadius: 16),
                  thumbShape: ThumbShape(),
                  trackHeight: 16,
                  trackShape: CustomTrackShape(4),
                  inactiveTickMarkColor: Colors.transparent,
                  activeTickMarkColor: Colors.transparent,
                  inactiveTrackColor: Colors.white,
                  activeTrackColor: Colors.white,
                  valueIndicatorColor: Colors.white),
              child: Slider(
                min: 0,
                max: 4,
                value: _cameraStartValue,
                divisions: 4,
                onChanged: (value) {
                  setState(() {
                    this._cameraStartValue = value;
                  });
                },
              ),
            ),
          ),
          Center(
            child: Row(
              children: <Widget>[
                Container(
                  width: (ScreenUtils.screenW(context) - 30)/5,
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.only(left: 15),
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        _cameraStartValue = 0.0;
                        widget?.uploadBean?.cameraStartDistance =_getDistance(_cameraStartValue);
                      });
                    },
                    child: Text(
                        "最近",
                        style: TextStyle(
                            color: 0.0 == _cameraStartValue ? Color(0xff1890ff) : Color(
                                0xffD0E0F7),
                            fontSize: 13)),
                  ),
                ),
                // _valueText("最近", 0.0),
                Container(
                  width: (ScreenUtils.screenW(context) - 30)/5,
                  alignment: Alignment.center,
                  padding: EdgeInsets.only(right: 7.5),
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        _cameraStartValue = 1.0;
                        widget?.uploadBean?.cameraStartDistance =_getDistance(_cameraStartValue);
                      });
                    },
                    child: Text(
                        "近",
                        style: TextStyle(
                            color: 1.0 == _cameraStartValue ? Color(0xff1890ff) : Color(
                                0xffD0E0F7),
                            fontSize: 13)),
                  ),
                ),
                _valueText("适中", 2.0),
                Container(
                  width: (ScreenUtils.screenW(context) - 30)/5,
                  alignment: Alignment.center,
                  padding: EdgeInsets.only(left: 7.5),
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        _cameraStartValue = 3.0;
                        widget?.uploadBean?.cameraStartDistance =_getDistance(_cameraStartValue);
                      });
                    },
                    child: Text(
                        "远",
                        style: TextStyle(
                            color: 3.0 == _cameraStartValue ? Color(0xff1890ff) : Color(
                                0xffD0E0F7),
                            fontSize: 13)),
                  ),
                ),
                Container(
                  width: (ScreenUtils.screenW(context) - 30)/5,
                  alignment: Alignment.centerRight,
                  padding: EdgeInsets.only(right: 15),
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        _cameraStartValue = 4.0;
                        widget?.uploadBean?.cameraStartDistance =_getDistance(_cameraStartValue);
                      });
                    },
                    child: Text(
                        "最远",
                        style: TextStyle(
                            color: 4.0 == _cameraStartValue ? Color(0xff1890ff) : Color(
                                0xffD0E0F7),
                            fontSize: 13)),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  _valueText(String text, double position) {
    return Container(
      width: (ScreenUtils.screenW(context) - 30)/5,
      alignment: Alignment.center,
      child: GestureDetector(
        onTap: () {
          setState(() {
            _cameraStartValue = position;
            widget?.uploadBean?.cameraStartDistance =_getDistance(_cameraStartValue);
          });
        },
        child: Text(
            text,
            style: TextStyle(
                color: position == _cameraStartValue ? Color(0xff1890ff) : Color(
                    0xffD0E0F7),
                fontSize: 13)),
      ),
    );
  }

  _valueImage(double position) {
    return Container(
      child: GestureDetector(
        onTap: () {
          setState(() {
            _faceSizeValue = position;
          });
        },
        child: Center(
            child: Image.asset(
              "images/icon_face_size_${_faceSizeValue == position?"":"un_"}select_${position.toInt().toString()}.png",
              width: 84,
              height: 149,
            )),
      ),
    );
  }

  _valueFrameText(String text, double position) {
    return Container(
      child: GestureDetector(
        onTap: () {
          setState(() {
            _faceSizeValue = position;
          });
        },
        child: Center(child: Text(
            text,
            style: TextStyle(
                color: position == _faceSizeValue ? Color(0xff1890ff) : Color(
                    0xffD0E0F7),
                fontSize: 13)),
        ),
      ),
    );
  }

  ///摄像头启动距离
  Widget _toCameraStartDistance(){
    return GestureDetector(
      onTap: ()async{
        double result= await CameraDistanceWidget.navigatorPush(context, widget?.uploadBean?.getCameraStartDistanceValue());
        if(result!=null){
          widget?.uploadBean?.cameraStartDistance =_getDistance(result);
          setState(() {});
        }
      },
      child: Container(
        height: 45,
        margin: const EdgeInsets.symmetric(horizontal: 15),
        padding: const EdgeInsets.symmetric(horizontal: 15),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8)),
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        ),
        child: Row(
          children: <Widget>[
            Text(
              "摄像头启动距离",
              style: TextStyle(
                  color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                  fontSize: 14
              ),
            ),

            Spacer(),
            Row(
              children: <Widget>[
                Text(
                  widget?.uploadBean == null?"-":widget?.uploadBean?.getCameraStartDistanceStr(),
                  style: TextStyle(
                      color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                      fontSize: 14
                  ),
                ),
                SizedBox(width: 9,),
                Image.asset(
                  "images/index_arrow_ico.png",
                  width: 6,
                )
              ],
            ),
          ],
        ),
      ),
    );
  }

  ///刷脸记录间隔
  Widget _toPunchInInterval(){
    return GestureDetector(
      onTap: (){
        return SelectUtil.showListSelectDialog(
            context: context,
            title: "刷脸记录间隔",
            positionStr: widget?.uploadBean?.getPunchInIntervalStr(),
            textList: ConstantRepository.of().getPunchInInterval(),
            onSelect: (dynamic value) {
              widget?.uploadBean?.punchInInterval = int.parse(value.toString().replaceAll("分钟", ""));
              setState(() {});
            }
        );
      },
      child: Container(
        height: 45,
        margin: const EdgeInsets.symmetric(horizontal: 15),
        padding: const EdgeInsets.symmetric(horizontal: 15),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8)),
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        ),
        child: Row(
          children: <Widget>[
            Text(
              "刷脸打卡间距",
              style: TextStyle(
                  color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                  fontSize: 14
              ),
            ),

            Spacer(),
            Row(
              children: <Widget>[
                Text(
                  widget?.uploadBean?.getPunchInIntervalStr(),
                  style: TextStyle(
                      color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                      fontSize: 14
                  ),
                ),
                SizedBox(width: 9,),
                Image.asset(
                  "images/index_arrow_ico.png",
                  width: 6,
                )
              ],
            ),
          ],
        ),
      ),
    );
  }

  ///自动开关机
  Widget _toAutoOnOff(){
    return GestureDetector(
      onTap: () async {
        Map<String, dynamic> resultMap =
        await BindingTerminalAutoSwitchDialog.navigatorPushDialog(
            context,
            widget?.uploadBean?.startDateTime,
            widget?.uploadBean?.endDateTime,
            widget?.uploadBean?.cameraStatusType ==
                BindingTerminalCameraStatusType.open);
        if (resultMap == null || resultMap.isEmpty) {
          return;
        }
        widget?.uploadBean?.startDateTime =
        resultMap[BINDING_TERMINAL_POP_START_DATE_TIME_KEY];
        widget?.uploadBean?.endDateTime =
        resultMap[BINDING_TERMINAL_POP_END_DATE_TIME_KEY];
        widget?.uploadBean?.autoOffStatusType =
        widget?.uploadBean?.startDateTime == null || widget?.uploadBean?.endDateTime == null
            ? BindingTerminalAutoOffStatusType.unSetting
            : BindingTerminalAutoOffStatusType.setting;
        widget?.uploadBean?.cameraStatusType =
        resultMap[BINDING_TERMINAL_POP_IS_ENABLE_SYNC_KEY]
            ? BindingTerminalCameraStatusType.open
            : BindingTerminalCameraStatusType.close;
        setState(() {});
      },
      child: Container(
        height: 45,
        margin: const EdgeInsets.symmetric(horizontal: 15),
        padding: const EdgeInsets.symmetric(horizontal: 15),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8)),
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        ),
        child: Row(
          children: <Widget>[
            Container(
              alignment: Alignment.centerLeft,
              child: Text(
                "自动开关机",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: ThemeRepository.getInstance()
                        .getTextMinorGreyColor_808388(),
                    fontSize: 14,
                    height: 1.2),
              ),
            ),
            Spacer(),
            Row(
              children: <Widget>[
                Text(
                  _getAutoTimeStr() ?? "暂未设置",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: widget?.uploadBean?.startDateTime == null ||
                          widget?.uploadBean?.endDateTime == null
                          ? ThemeRepository.getInstance()
                          .getTextEditHintColor_3A3F50()
                          : Colors.white,
                      fontSize: 14,
                      height: 1.2),
                ),
                SizedBox(width: 9,),
                Image.asset(
                  "images/index_arrow_ico.png",
                  width: 6,
                )
              ],
            ),
          ],
        ),
      ),
    );
  }

  String _getAutoTimeStr() {
    if (widget?.uploadBean?.endDateTime == null || widget?.uploadBean?.startDateTime == null) {
      return null;
    }

    return "${VgToolUtils.twoDigits(widget?.uploadBean?.startDateTime.hour)}:${VgToolUtils.twoDigits(widget?.uploadBean?.startDateTime.minute)}" +
        "至" +
        "${VgToolUtils.twoDigits(widget?.uploadBean?.endDateTime.hour)}:${VgToolUtils.twoDigits(widget?.uploadBean?.endDateTime.minute)}";
  }
}